package com.hmdp.service.impl;

import ch.qos.logback.classic.spi.EventArgUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询博客信息
     */
    @Override
    public Result queryBlog(Long id) {
        // 1 查询博客信息
        Blog blog = getById(id);
        // 2 封装昵称和头像到blog
        if(blog == null){
            return Result.fail("笔记不存在!");
        }
        setUserToBlog(blog);
        // 3 查询博客是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    /**
     * 热门博客
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            setUserToBlog(blog);
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 点赞
     */
    @Override
    public Result likeBlog(Long id) {
        //        blogService.update().setSql("liked = liked + 1").eq("id", id).update();
        // 1 判断当前用户是否点赞 怎么判断? 看set集合里有没有userid
        Long userId = UserHolder.getUser().getId();
        // set集合 sadd sismember
        // sortedSet zadd zscore
        String key = BLOG_LIKED_KEY + id;
//        Boolean isLike = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double isLike = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        // 2 点过赞 取消点赞 从set里删除
//        if(BooleanUtil.isTrue(isLike)){
        if(isLike != null){ // 找到sorce
            // 点赞数 -1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if(BooleanUtil.isTrue(isSuccess)){
                // 从set删除
//                stringRedisTemplate.opsForSet().remove(key, String.valueOf(userId));
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }

        }else{
            // 3 没点过 点赞 加入到set集合
            // 3.1 数据库点赞+1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if(BooleanUtil.isTrue(isSuccess)){
                // 3.2 写入redis
                double timeStamp = System.currentTimeMillis();
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), timeStamp);
            }
        }
        return Result.ok();
    }

    /**
     * 上传博客
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("上传笔记失败!");
        }
        Long blogId = blog.getId();
        // 上传博客成功，将博客id推送至粉丝收件箱
        String getFansKey = BLOG_FOLLOW_KEY + user.getId();
        Set<String> fansSet = stringRedisTemplate.opsForZSet().range(getFansKey, 0, -1);
        // 没有粉丝 直接返回博客id，不进行推送
        if(fansSet == null || fansSet.isEmpty()){
            return Result.ok(blogId);
        }
        List<Long> fansIds = fansSet.stream().map(Long::valueOf).collect(Collectors.toList());
        // 将推送信息存储在redis中
        fansIds.forEach(fansId -> stringRedisTemplate.opsForZSet()
                    .add(BLOG_FEED_KEY + fansId, blogId.toString(), System.currentTimeMillis()));
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 点赞排行榜
     */
    @Override
    public Result likeTop5(Long id) {
        // 1 从redis中获取点赞的score前五名的id
        String key = BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5 == null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 解析用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        // 2 查询Top5用户的信息 // where in(xx,xx) 不做排序，需要在后面加上 order by field(id, xx, xx)
        List<User> users = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id, " + idStr + ")").list();
        List<UserDTO> userDTOList = users.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 3 返回List<UserDTO>
        return Result.ok(userDTOList);
    }

    /**
     * 个人信息页面分页查询笔记
     * @param blogerId
     * @param currentPage
     * @return
     */
    @Override
    public Result queryBlogByPage(Long blogerId, Integer currentPage) {
        // 1 根据blogerId分页查询他的笔记
        Page<Blog> page = query()
                .eq("user_id", blogerId)
                .orderByDesc("create_time")
                .page(new Page<>(currentPage, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 2 看当前登录的用户有没有对笔记点赞
        records.forEach(this::isBlogLiked);
        // 3 返回数据
        return Result.ok(records);
    }

    /**
     * 滚动分页查询
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 从redis中拿到feed数据
        String key = BLOG_FEED_KEY + UserHolder.getUser().getId();
        // ZREVRANGEBYSCORE key max min LIMIT offset count
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key,0, max, offset, 2);
        // 解析数据，需要 笔记id score
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            // 获取id
            String idStr = tuple.getValue();
            ids.add(Long.valueOf(idStr));
            // 获取时间戳
            long time = tuple.getScore().longValue();
            if(time == minTime){
                os++;
            }else{
                minTime = time;
                os = 1;
            }
        }
        // 根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogList = query()
                .in("id", ids).last("ORDER BY FIELD(id, " + idStr + ")").list();
        blogList.forEach(blog -> {
            setUserToBlog(blog);
            isBlogLiked(blog);
        });
        // 封装
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }


    // 查询博客是否被点赞
    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user == null){
            // 用户未登录，无需查询是否点赞
            return ;
        }
        String key = BLOG_LIKED_KEY + blog.getId();
        Double isLike = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());
        blog.setIsLike(isLike != null);


    }

    // 封装用户昵称和头像到blog
    private void setUserToBlog(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
